package com.dyna.event;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.dyna.core.exception.CustomException;
import com.dyna.domain.build.VirtualLockerBuild;
import com.dyna.domain.entity.VirtualLocker;
import com.dyna.domain.event.WarehouseEvent;
import com.dyna.mapper.ItemsMapper;
import com.dyna.mapper.VirtualLockerMapper;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Component
public class WarehouseEventListener {

    private final ItemsMapper itemsMapper;
    private final VirtualLockerMapper virtualLockerMapper;

    public WarehouseEventListener(ItemsMapper itemsMapper, VirtualLockerMapper virtualLockerMapper) {
        this.itemsMapper = itemsMapper;
        this.virtualLockerMapper = virtualLockerMapper;
    }

    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT, classes = WarehouseEvent.class, fallbackExecution = true)
    public void messageRoute(WarehouseEvent event) {
        // 数据库库存扣减（原子操作）
        boolean dbSuccess = itemsMapper.reduceCount(event.getItemId(), event.getCount());
        if (!dbSuccess) {
            throw new CustomException("扣减数据库库存失败");
        }

        // 保存购买记录
        VirtualLockerBuild build = VirtualLockerBuild.builder()
                .lockerId(IdUtil.getSnowflakeNextId())
                .userId(event.getUserId())
                .skuId(event.getItemId())
                .purchasePrice(BigDecimal.ZERO)
                .finalPayAmount(BigDecimal.ZERO)
                .count(event.getCount())
                .expireTime(LocalDateTime.now().plusYears(99))
                .build();
        VirtualLocker virtualLocker = BeanUtil.copyProperties(build, VirtualLocker.class);
        boolean saveSuccess = virtualLockerMapper.insert(virtualLocker) > 0;
        if (!saveSuccess) {
            // 保存记录失败，回滚库存
            throw new CustomException("保存购买记录失败");
        }
    }

}
